package com.nth.rooster.core.exception;

import java.text.MessageFormat;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class RoosterExceptionResolver{

	@Autowired  
	@Qualifier("errorCode") 
	private Properties properties;
	
	static Logger LOGGER = Logger.getLogger(RoosterExceptionResolver.class);
	
	
		@ExceptionHandler(RoosterCoreException.class)
		@ResponseBody
		public ErrorBean resolveException(final Exception exception) {

			LOGGER.info("Entered::RoosterExceptionResolver::resolveException");
			String errorCode = null;
			String errorMessage = null;

			RoosterCoreException roosterCoreException = null;

			if (exception instanceof RoosterCoreException) {
				
				roosterCoreException = (RoosterCoreException) exception;
				NErrorCode nErrorCode = roosterCoreException.getNErrorCode();
				if (null != nErrorCode) {
					errorCode = String.valueOf(nErrorCode.getErrorCode());
					errorMessage = properties.getProperty(errorCode);
				}

				Object[] params = roosterCoreException.getParams();
				if (params != null) {
					MessageFormat mf = new MessageFormat(errorMessage);
					errorMessage = mf.format(params, new StringBuffer(), null)
							.toString();
				}
				
				LOGGER.error(errorMessage,exception);

			} else if (exception instanceof RuntimeException) {

				// IMPLEMENT ANY TYPE OF EXCEPTION
			}

			ErrorBean modelAndView = new ErrorBean();
			modelAndView.setErrorCode(errorCode);
			LOGGER.info("RoosterExceptionResolver::resolveException::ErrorCode::" + errorCode);

			modelAndView.setErrorMessage(errorMessage);
			LOGGER.info("RoosterExceptionResolver::resolveException::ErrorMessage::" + errorMessage);

			LOGGER.info("Exited::RoosterExceptionResolver::resolveException");
			return modelAndView;

		}

}
